import sys

from PySide6.QtCore import Signal
from PySide6.QtWidgets import QApplication, QPushButton, QWidget, QVBoxLayout, QLineEdit, QLabel


class TransformSignal(object):
    """
    窗口间通信信号
    """
    # DOC: 1. 自定义通信信号
    transformSignal = Signal(str)

    def sendAndEmit(self):
        """
        发送和触发信号
        :return: 
        """
        raise NotImplementedError

    def receive(self, text):
        """
        接收信号后的处理方法
        :param text: 
        :return: 
        """
        raise NotImplementedError


class MyWindow(QWidget, TransformSignal):

    def __init__(self) -> None:
        super().__init__()
        self.subWindow = None
        self.setWindowTitle("MyWindow")
        self.lineEdit = QLineEdit()
        self.lineEdit.setPlaceholderText('主窗口文本框')
        self.button = QPushButton("Press me")
        self.button.clicked.connect(self.sendAndEmit)

        self.mainLayout = QVBoxLayout()
        self.mainLayout.addWidget(self.lineEdit)
        self.mainLayout.addWidget(self.button)
        self.setLayout(self.mainLayout)
        # 绑定子窗口 & 信号绑定槽
        self.bind()

    def bind(self):
        """
        绑定子窗口和信号的初始化
        :return:
        """
        self.subWindow = SubWindow(self)
        # DOC: 2. 【绑定 connect】把【信号绑定到槽（接收信号后的处理函数）】
        self.transformSignal.connect(self.subWindow.receive)
        self.subWindow.show()

    def receive(self, text):
        self.lineEdit.setText(text)

    def sendAndEmit(self):
        text = self.lineEdit.text()
        # DOC: 3. 【触发 emit】触发信号
        self.transformSignal.emit(text)


class SubWindow(QWidget, TransformSignal):

    def __init__(self, parent=None):
        super().__init__()
        self.parent = parent
        self.lb = QLabel('这是子窗口')
        self.lineEdit = QLineEdit()
        self.lineEdit.setPlaceholderText('子窗口文本框')
        self.button = QPushButton("Press me")
        self.button.clicked.connect(self.sendAndEmit)

        self.mainLayout = QVBoxLayout()
        self.mainLayout.addWidget(self.lb)
        self.mainLayout.addWidget(self.lineEdit)
        self.mainLayout.addWidget(self.button)
        self.setLayout(self.mainLayout)
        self.bind()

    def bind(self):
        """
        绑定子窗口和信号的初始化
        :return:
        """
        # DOC: 2. 【绑定 connect】把【信号绑定到槽（接收信号后的处理函数）】
        self.transformSignal.connect(self.parent.receive)

    def receive(self, text):
        self.lineEdit.setText(text)

    def sendAndEmit(self):
        text = self.lineEdit.text()
        # DOC: 3. 【触发 emit】触发信号
        self.transformSignal.emit(text)


if __name__ == '__main__':
    app = QApplication(sys.argv)

    window = MyWindow()
    window.show()

    app.exec()
